<script setup>
import {ref, reactive, onMounted} from 'vue'
import {Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {listNews, addNews, updateNews, deleteNews} from '@/api/business/news.js'

// 新闻表列表数据
const newsList = ref([])
const tableLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: ''  // 搜索关键字
})

// 弹窗表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const form = reactive({
  id: null,
  title: '',
  content: '',
  publishTime: null,
  authorId: null
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入新闻内容', trigger: 'blur' }]
}

const formRef = ref(null)

// 获取新闻表列表数据
const getNewsList = async () => {
  tableLoading.value = true
  try {
    const res = await listNews({
      ...pagination,
      keyword: searchForm.keyword
    })
    if (res.code === 200) {
      newsList.value = res.data.list
      pagination.total = res.data.total
    } else {
      ElMessage.error(res.msg || '获取新闻列表失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '获取新闻列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 打开新增弹窗
const handleAdd = () => {
  dialogTitle.value = '新增新闻'
  Object.keys(form).forEach(key => form[key] = null)
  form.publishTime = new Date()
  dialogVisible.value = true
}

// 打开编辑弹窗
const handleEdit = (row) => {
  dialogTitle.value = '编辑新闻'
  Object.keys(form).forEach(key => form[key] = row[key])
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      formLoading.value = true;
      try {
        // 确保 publishTime 是一个有效的 Date 对象
        const publishTime = form.publishTime instanceof Date ? form.publishTime : new Date(form.publishTime);

        // 转换日期格式，确保格式为 "yyyy-MM-dd HH:mm:ss"
        const publishTimeStr = publishTime.getFullYear() + '-' +
          ('0' + (publishTime.getMonth() + 1)).slice(-2) + '-' +
          ('0' + publishTime.getDate()).slice(-2) + ' ' +
          ('0' + publishTime.getHours()).slice(-2) + ':' +
          ('0' + publishTime.getMinutes()).slice(-2) + ':' +
          ('0' + publishTime.getSeconds()).slice(-2);

        form.publishTime = publishTimeStr; // 将格式化后的字符串赋值给 form.publishTime

        const api = form.id ? updateNews : addNews;
        const res = await api(form);
        if (res.code === 200) {
          ElMessage.success(form.id ? '更新成功' : '新增成功');
          dialogVisible.value = false;
          getNewsList();
        } else {
          ElMessage.error(res.msg || (form.id ? '更新失败' : '新增失败'));
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.msg || (form.id ? '更新失败' : '新增失败'));
      } finally {
        formLoading.value = false;
      }
    }
  });
};

// 删除新闻
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该新闻吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteNews(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getNewsList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.msg || '删除失败')
    }
  })
}

// 在组件挂载时获取数据
onMounted(() => {
  getNewsList()
})

// 分页相关数据
const pagination = reactive({
  // 每页显示的数据条数
  size: 20,
  // 当前页码，从1开始
  page: 1,
  // 总数据条数，会在获取数据时更新
  total: 0
})

// 分页变化处理函数
const handleCurrentChange = async (val) => {
  pagination.page = val
  await getNewsList()
}

const handleSizeChange = async (val) => {
  pagination.size = val
  pagination.page = 1
  await getNewsList()
}

const handleRefresh = () => {
  getNewsList()
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1  // 重置到第一页
  getNewsList()
}

// 重置搜索
const handleReset = () => {
  searchForm.keyword = ''
  handleSearch()
}
</script>

<template>
  <div class="news-container">
    <!-- 顶部按钮 -->
    <div class="top-tools">
      <div class="left">
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
      </div>
      <div class="right">
        <el-form :inline="true" :model="searchForm" @submit.prevent>
          <el-form-item class="mb0">
            <el-input
                    v-model="searchForm.keyword"
                    placeholder="请输入关键词"
                    clearable
            />
          </el-form-item>
          <el-form-item class="mb0">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 新闻表列表 -->
    <el-table

      :data="newsList"
      v-loading="tableLoading"
      :table-layout="'auto'"
      style="width: 100%"
      border
    >

      <el-table-column type="index" width="50" label="序号" />
      <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
      <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
      <el-table-column prop="publishTime" label="发布时间" width="160" />
      <el-table-column prop="authorId" label="作者ID" width="100" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle @click="handleEdit(row)" />
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" rows="6" placeholder="请输入新闻内容" />
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="form.publishTime"
            type="datetime"
            placeholder="选择发布时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="formLoading" @click="submitForm">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.news-container {
  padding: 20px;
}

.top-tools {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.top-tools .left {
  display: flex;
  gap: 10px;
}

.top-tools .right {
  display: flex;
  align-items: center;
  margin-left: auto;

  .el-form .el-form-item:last-child {
    margin-right: 0;
  }
}

@media screen and (max-width: 768px) {
  .top-tools {
    flex-direction: column;
    align-items: flex-start;
  }

  .top-tools .right {
    margin-left: 0;
    width: 100%;
  }
}

.mb0 {
  margin-bottom: 0;
}

.el-form--inline .el-form-item {
  margin-right: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
